<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <h3 class="mb-4">编辑帖子</h3>
      </div>
    </div>
    
    <form @submit.prevent="updatePost">
      <!-- 封面图片区域 -->
      <div class="row mb-4">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <h5 class="card-title mb-0">封面图片</h5>
            </div>
            <div class="card-body">
              <!-- 现有图片上传区域 -->
              <div class="cover-image-preview mb-3">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  name="file"
                  :before-upload="beforeCoverUpload"
                  :http-request="handleCoverUpload"
                  :on-error="handleCoverError"
                  :show-file-list="false"
                >
                  <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传新图片</div>
                </el-upload>
              </div>
              
              <!-- 显示所有已有的封面图片 -->
              <div class="existing-images-section" v-if="existingImages.length > 0">
                <h6>已有图片</h6>
                <div class="image-grid">
                  <div 
                    v-for="(image, index) in existingImages" 
                    :key="index" 
                    class="image-item"
                  >
                    <img 
                      :src="image.url" 
                      class="existing-image" 
                      @click="showImagePreview(index)"
                    />
                    <div class="image-actions">
                      <el-button 
                        type="danger" 
                        size="small" 
                        @click="removeImage(image.id)"
                        circle
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="d-grid gap-2">
                <button 
                  type="button" 
                  class="btn btn-outline-primary"
                  :disabled="existingImages.length === 0"
                  @click="showImagePreview(0)"
                >
                  查看图片
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 帖子基本信息 -->
      <div class="row">
        <div class="col-lg-8">
          <div class="card">
            <div class="card-header">
              <h5 class="card-title mb-0">基本信息</h5>
            </div>
            <div class="card-body">

              <div class="mb-3">
                <label for="categoryId" class="form-label">板块 *</label>
                <select 
                  class="form-select" 
                  id="categoryId" 
                  v-model="formData.categoryId" 
                  required
                  @change="fetchItemType"
                >
                  <option 
                    v-for="category in categories" 
                    :key="category.id" 
                    :value="category.id"
                    :class="{ 'hover': categoryHover === category.id }"
                    @mouseenter="categoryHover = category.id"
                    @mouseleave="categoryHover = null"
                  >
                    {{ category.name }}
                  </option>
                </select>
              </div>

              <!-- 详细分类 -->
              <div class="mb-3" v-if="itemType.length > 0">
                <label for="itemTypeId" class="form-label">详细分类</label>
                <select 
                  class="form-select" 
                  id="itemTypeId" 
                  v-model="formData.itemTypeId"
                >
                  <option value="">请选择详细分类</option>
                  <option 
                    v-for="item in itemType" 
                    :key="item.id" 
                    :value="item.id"
                  >
                    {{ item.name }}
                  </option>
                </select>
                <div class="form-text">根据所选版块分类，提供相应的详细分类选项</div>
              </div>

              <div class="mb-3">
                <label for="title" class="form-label">标题 *</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="title" 
                  v-model="formData.title" 
                  required
                >
              </div>
              
              <div class="mb-3">
                <label for="content" class="form-label">内容 *</label>
                <textarea 
                  class="form-control" 
                  id="content" 
                  rows="6" 
                  v-model="formData.content" 
                  required
                ></textarea>
              </div>
            </div>
          </div>
        </div>
        
        <div class="col-lg-4">
          <div class="card mb-4">
            <div class="card-header">
              <h5 class="card-title mb-0">属性设置</h5>
            </div>
            <div class="card-body">
              <div class="mb-3">
                <label for="price" class="form-label">价格 (元)</label>
                <input 
                  type="number" 
                  class="form-control price-input" 
                  id="price" 
                  v-model="formData.price" 
                  step="0.01"
                  min="0"
                >
              </div>
              
              <div class="mb-3">
                <label for="location" class="form-label">地点</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="location" 
                  v-model="formData.location"
                >
              </div>
              
              <div class="mb-3">
                <label for="contactInfo" class="form-label">联系方式</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="contactInfo" 
                  v-model="formData.contactInfo"
                >
              </div>
              
              <div class="mb-3">
                <label for="status" class="form-label">状态</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="status" 
                  :value="formatStatus(formData.status)" 
                  readonly
                >
              </div>
              
              <div class="mb-3">
                <el-switch
                  v-model="formData.isUrgent"
                  active-text="标记为紧急"
                />
              </div>
              
              <div class="mb-3">
                <label for="expiredAt" class="form-label">过期时间</label>
                <el-date-picker
                  v-model="formData.expiredAt"
                  type="datetime"
                  placeholder="选择日期和时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="w-100"
                />
              </div>
            </div>
          </div>
          
          <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <button type="button" class="btn btn-secondary me-md-2" @click="goBack">
              返回
            </button>
            <button type="submit" class="btn btn-primary">
              保存更改
            </button>
          </div>
        </div>
      </div>
    </form>
    
    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="图片预览" width="600px" center>
      <div class="image-preview-container">
        <div class="image-navigation" v-if="existingImages.length > 1">
          <el-button 
            circle 
            :disabled="currentPreviewIndex <= 0" 
            @click="prevImage"
          >
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          
          <span class="image-counter">
            {{ currentPreviewIndex + 1 }} / {{ existingImages.length }}
          </span>
          
          <el-button 
            circle 
            :disabled="currentPreviewIndex >= existingImages.length - 1" 
            @click="nextImage"
          >
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        
        <img 
          :src="existingImages[currentPreviewIndex]?.url" 
          class="preview-large-image" 
          v-if="imagePreviewVisible && existingImages.length > 0" 
        />
        
        <div class="no-image-placeholder" v-else>
          暂无图片
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElUpload, ElIcon, ElDialog, ElSwitch, ElButton, ElMessageBox } from 'element-plus'
import { Plus, Delete, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import axios from '@/utils/request.js'
import { getPostListService,
         getCategoriesListService, 
         getPostCoverService,
         updatePostService,
         deletePostCoverService,
         getPostTypesService } from '@/api/post.js'

const route = useRoute()
const router = useRouter()

// 表单数据
const formData = ref({
  id: null,
  title: '',
  content: '',
  categoryId: null,
  itemTypeId: null, // 添加详细分类字段
  contactInfo: '',
  price: null,
  location: '',
  status: 'pending',
  isUrgent: false,
  coverImage: '',
  expireTime: ''
})

// 已有的图片列表
const existingImages = ref([])

// 分类列表
const categories = ref([])

// 详细分类列表
const itemType = ref([])

// 分类悬停状态
const categoryHover = ref(null)

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    sold: '已售出'
  }
  return statusMap[status] || status
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoriesListService()
    categories.value = res.data
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类信息失败')
  }
}

// 获取详细分类
const fetchItemType = async () => {
  // 只有当 categoryId 为 1 或 2 时才获取详细分类
  if (formData.value.categoryId !== 1 && formData.value.categoryId !== 2) {
    itemType.value = []
    formData.value.itemTypeId = null
    return
  }
  
  try {
    const response = await getPostTypesService(formData.value.categoryId)
    itemType.value = response.data || []
    console.log('详细分类数据:', itemType.value)
  } catch (error) {
    console.error('获取详细分类失败:', error)
    itemType.value = []
    formData.value.itemTypeId = null
  }
}

// 获取帖子详情
const fetchPostDetail = async (postId) => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100 // 获取足够多的数据以找到目标帖子
    }
    
    // 获取帖子列表
    const res = await getPostListService(params)
    // 查找目标帖子
    const post = res.data.items.find(item => item.id === parseInt(postId))
    
    if (post) {
      // 获取封面图片
      let coverImages = []
      try {
        const coverRes = await getPostCoverService()
        if (coverRes && coverRes.data) {
          // 获取该帖子的所有图片
          coverImages = coverRes.data.filter(img => img.postId === post.id)
          // 处理图片URL
          coverImages = coverImages.map(img => ({
            id: img.id,
            url: img.imageUrl.startsWith('http') 
              ? img.imageUrl 
              : `http://localhost:8080${img.imageUrl}`
          }))
        }
      } catch (error) {
        console.error('获取封面图片失败:', error)
      }
      
      // 设置已有的图片
      existingImages.value = coverImages
      
      formData.value = {
        id: post.id,
        title: post.title,
        content: post.content,
        categoryId: post.categoryId,
        itemTypeId: post.itemTypeId, // 设置详细分类
        contactInfo: post.contactInfo,
        price: post.price,
        location: post.location,
        status: post.status,
        isUrgent: post.isUrgent,
        coverImage: coverImages.length > 0 ? coverImages[0].url : '', // 默认显示第一张图片
        expiredAt: post.expiredAt
      }
      
      // 获取详细分类数据
      if (post.categoryId) {
        await fetchItemType()
      }
    } else {
      ElMessage.error('未找到该帖子')
      router.back()
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
    router.back()
  }
}

// 删除图片
const removeImage = async (imageId) => {
  ElMessageBox.confirm(
    '确定要删除这张图片吗？此操作不可恢复！',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 从已有的图片列表中删除图片
        existingImages.value = existingImages.value.filter(img => img.id !== imageId)
        await deletePostCoverService(imageId)
        
        // 如果删除的是当前显示的封面图片，则更新为第一张图片或清空
        if (formData.value.coverImage && existingImages.value.length > 0) {
          formData.value.coverImage = existingImages.value[0].url
        } else if (existingImages.value.length === 0) {
          formData.value.coverImage = ''
        }
        
        ElMessage.success('图片删除成功')
      } catch (error) {
        console.error('删除图片失败:', error)
        ElMessage.error('删除图片失败')
      }
    })
    .catch(() => {
      // 用户取消删除
      ElMessage.info('已取消删除')
    })
}

// 图片预览相关
const imagePreviewVisible = ref(false)
const currentPreviewIndex = ref(0)

// 显示图片预览
const showImagePreview = (index = 0) => {
  if (existingImages.value.length > 0) {
    currentPreviewIndex.value = index
    imagePreviewVisible.value = true
  }
}

// 上一张图片
const prevImage = () => {
  if (currentPreviewIndex.value > 0) {
    currentPreviewIndex.value--
  }
}

// 下一张图片
const nextImage = () => {
  if (currentPreviewIndex.value < existingImages.value.length - 1) {
    currentPreviewIndex.value++
  }
}

//处理封面图片上传
const handleCoverUpload = async (options) => {
  const { file } = options;
  
  // 创建 FormData 对象
  const uploadFormData = new FormData();
  uploadFormData.append('file', file);
  uploadFormData.append('postId', formData.value.id); 
  
  try {
    // 直接调用后端uploadCover接口，同时上传文件并关联到帖子
    const res = await axios.patch('/uploadCover', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (res.data.code === 0) {
      const imageUrl = res.data.data;
      const fullImageUrl = imageUrl.startsWith('http') 
        ? imageUrl 
        : `http://localhost:8080${imageUrl}`;
      
      // 添加到现有图片列表
      const newImage = {
        id: Date.now(), // 临时ID，实际应该使用服务器返回的ID
        url: fullImageUrl
      };
      existingImages.value.push(newImage);
      
      // 如果还没有封面图片，则设置为第一张
      if (!formData.value.coverImage) {
        formData.value.coverImage = fullImageUrl;
      }
      
      console.log('上传成功:', fullImageUrl);
      ElMessage.success('封面图片上传成功');
    } else {
      throw new Error(res.data.msg || '上传失败');
    }
    
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error(error.message || '封面图片上传失败');
  }
};


// 添加上传前确认提示
const beforeCoverUpload = (rawFile) => {
  // 添加确认提示
  const confirmed = window.confirm('确定要上传这张图片作为封面吗？');
  if (!confirmed) {
    return false;
  }
  
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('封面图片必须是 JPG 或 PNG 格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('封面图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 添加上传错误处理
const handleCoverError = (error) => {
  console.error('上传失败:', error);
  ElMessage.error('封面图片上传失败');
};

// 更新帖子
const updatePost = async () => {
  try {
    // 准备要发送到后端的数据
    const postData = {
      id: formData.value.id,
      title: formData.value.title,
      content: formData.value.content,
      categoryId: formData.value.categoryId,
      itemTypeId: formData.value.itemTypeId, // 添加详细分类字段
      contactInfo: formData.value.contactInfo,
      price: formData.value.price ? parseFloat(formData.value.price) : null,
      location: formData.value.location,
      isUrgent: formData.value.isUrgent,
      expiredAt: formData.value.expiredAt,
      coverImage: formData.value.coverImage // 添加封面图片字段
    }
    await updatePostService(postData)
    ElMessage.success('帖子更新成功')
    router.push('/user/posts')
  } catch (error) {
    console.error('更新帖子失败:', error)
    ElMessage.error('更新帖子失败')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(async () => {
  const postId = route.params.id
  if (postId) {
    await fetchCategories()
    await fetchPostDetail(postId)
  } else {
    ElMessage.error('无效的帖子ID')
    router.back()
  }
})
</script>

<style scoped>
.cover-image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px;
  background-color: #f8f9fa;
  border-radius: 0.375rem;
  flex-direction: column;
}

.upload-text {
  margin-top: 10px;
  color: #6c757d;
}

.existing-images-section {
  margin: 20px 0;
}

.existing-images-section h6 {
  margin-bottom: 10px;
  color: #333;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.image-item {
  position: relative;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.existing-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
  display: block;
  transition: transform 0.2s;
}

.existing-image:hover {
  transform: scale(1.05);
}

.image-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

.image-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.image-counter {
  font-weight: bold;
  color: #333;
}

.no-image-placeholder {
  text-align: center;
  color: #6c757d;
  padding: 20px;
}

.card {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  border: 1px solid rgba(0, 0, 0, 0.125);
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}

.avatar-uploader .avatar {
  width: 100%;
  max-height: 200px;
  display: block;
  object-fit: contain;
}

.preview-image {
  transition: transform 0.3s ease;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.image-preview-container {
  text-align: center;
}

.preview-large-image {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
}

/* 新增样式：加粗加大label标签字体 */
.form-label {
  font-weight: bold;
  font-size: 1.1em;
}

/* 修改样式：将h5标签字体颜色改为蓝色，而不是背景色 */
.card-header h5 {
  color: #0d6efd;
  margin: 0;
}

/* 新增样式：价格输入框文字为红色 */
.price-input {
  color: #dc3545;
}

/* 新增样式：状态选项颜色 */
.status-pending {
  color: #ffc107;
}

.status-approved {
  color: #28a745;
}

.status-rejected {
  color: #dc3545;
}

.status-sold {
  color: #6c757d;
}
</style>